import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.net.NetConnection;
import flash.net.Responder;
import fl.data.DataProvider;
typedef PlayerData =
{
	var id : Int;
	var name : String;
	var x : Float;
	var y : Float;
	var rotation : Float;
	var health : Float;
}
class Lobby extends Panel
{
	var container : Sprite;
	var chat:Chat;
	var allPlayers:fl.controls.List;
	var waitingPlayers:fl.controls.List;
	var gamesInPlay:fl.controls.List;
	var gamesHistory:fl.controls.List;
	
	var startGameBtn:fl.controls.Button;
	var joinGameBtn:fl.controls.Button;
	var watchGameBtn:fl.controls.Button;
	var replayGameBtn:fl.controls.Button;

	var controller:Dynamic;
	var background:Sprite;
	var client:Dynamic;
	var connection:NetConnection;
	var console:Console;
	var lastGameId:Float;
	var selectedGameId:Float;
	var userName:String;
	public function new(connection, console, userName)
	{
		super();
		this.connection = connection;
		connection.client=this;
		this.console = console;
		this.userName = userName;
		
		container = createView();
		addChild(container);
		minWidth=container.width+100;
		minHeight=container.height+120;

		setSize(minWidth, minHeight);
		
		updateUserList();
		updateHistoryList();
		updateGamesInPlayList();
		addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
	}
	function onAddedToStage(event:Event):Void
	{
		removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		stage.addEventListener(Event.RESIZE, onStageResize);
		onStageResize(null);
		onResize(null);
	}
	function onStageResize(event:Event):Void
	{
		if(visible && stage!=null)
		{
			x = (stage.stageWidth - width)/2;
			y = (stage.stageHeight - height)/2;
		}
	}
	override function onResize(event:MouseEvent):Void
	{
		super.onResize(event);//setSize(stage.mouseX-this.x+15, stage.mouseY-this.y+15);
		container.x = (w - container.width)/2;
		container.y = (h - container.height)/2;
	}

	function createView()
	{
		var container = new Sprite();
		
		chat = new Chat(connection, userName);
		container.addChild(chat);
		
		allPlayers = new fl.controls.List();
		//container.addChild(allPlayers);
		
		waitingPlayers = new fl.controls.List();
		waitingPlayers.addEventListener(Event.CHANGE, onGameListSelect);
		container.addChild(waitingPlayers);
		
		gamesInPlay = new fl.controls.List();
		gamesInPlay.addEventListener(Event.CHANGE, onGameListSelect);
		container.addChild(gamesInPlay);
		
		gamesHistory = new fl.controls.List();
		gamesHistory.addEventListener(Event.CHANGE, onGameListSelect);
		container.addChild(gamesHistory);

		startGameBtn = new fl.controls.Button();
		startGameBtn.label = 'start a game';
		startGameBtn.addEventListener(MouseEvent.CLICK, onStartGameBtn);
		container.addChild(startGameBtn);
		
		joinGameBtn = new fl.controls.Button();
		joinGameBtn.label = "join a game";
		joinGameBtn.addEventListener(MouseEvent.CLICK, onJoinGameBtn);
		container.addChild(joinGameBtn);
		
		watchGameBtn = new fl.controls.Button();
		watchGameBtn.label = "watch a game";
		watchGameBtn.addEventListener(MouseEvent.CLICK, onWatchGameBtn);
		container.addChild(watchGameBtn);
		
		replayGameBtn = new fl.controls.Button();
		replayGameBtn.label = "replay a game";
		replayGameBtn.addEventListener(MouseEvent.CLICK, onReplayGameBtn);
		container.addChild(replayGameBtn);
		
		allPlayers.x	 = startGameBtn.x	=  0;
		waitingPlayers.x = joinGameBtn.x	= 200;
		gamesInPlay.x	 = watchGameBtn.x	= 400;
		gamesHistory.x	 = replayGameBtn.x	= 600;
		
		allPlayers.y = waitingPlayers.y = gamesInPlay.y = gamesHistory.y = 0;
		
		startGameBtn.y	= allPlayers.y		+ allPlayers.height;
		joinGameBtn.y	= waitingPlayers.y	+ waitingPlayers.height;
		watchGameBtn.y	= gamesInPlay.y		+ gamesInPlay.height;
		replayGameBtn.y	= gamesHistory.y	+ gamesHistory.height;
		
		chat.y = startGameBtn.y + startGameBtn.height + 10;

		allPlayers.width = waitingPlayers.width = gamesInPlay.width = gamesHistory.width =
		startGameBtn.width = joinGameBtn.width = watchGameBtn.width = replayGameBtn.width = 150;
		
		allPlayers.labelField="name";
		waitingPlayers.labelFunction = function(obj) 
		{
			if(obj.players[1]==null || obj.players[1]=="")
				return obj.players[0]+" vs you?";
			return obj.players[0]+" vs " +obj.players[1];
		}
		gamesInPlay.labelFunction = function(obj) return obj.players[0]+" vs " +obj.players[1];
		gamesHistory.labelField="name";

		return container;
	}
	function onGameListSelect(event:Event)
	{
		selectedGameId = event.currentTarget.selectedItem.id;
		console.log("selectedGameId:" + event.currentTarget.selectedItem.id);
	}
	function onStartGameBtn(event:MouseEvent)
	{
		connection.call("getGameId", new Responder(onGetGameId, console.log));
	}
	function onGetGameId(nr:Float)
	{
		lastGameId = nr;
		this.dispatchEvent(new Event("newGame"));
	}
	public function getGameId():Float
	{
		return lastGameId;
	}
	function onJoinGameBtn(event:MouseEvent)
	{
		if(waitingPlayers.selectedItem!=null)
		{
			var label = waitingPlayers.itemToLabel(waitingPlayers.selectedItem);
			if(label != userName+" vs you?")
			{
				lastGameId = waitingPlayers.selectedItem.id;
				this.dispatchEvent(new Event("newGame"));
			}
			else
			{
				console.log("You cannot play against yourself");
			}
		}
	}
	function onWatchGameBtn(event:MouseEvent)
	{
		if(gamesInPlay.selectedItem!=null)
		{
			lastGameId = gamesInPlay.selectedItem.id;
			this.dispatchEvent(new Event("newGame"));
		}
	}
	function onReplayGameBtn(event:MouseEvent)
	{
		if(gamesHistory.selectedItem!=null)
		{
			lastGameId = Std.parseFloat(gamesHistory.selectedItem.name.split("so").join("").split(".hx").join(""));
			this.dispatchEvent(new Event("newGame"));
		}
	}
	
	function onPlayerJoin(data:PlayerData)
	{
		console.log("<" + data.name+"> has joined.");
		chat.onPlayerJoin(data);
		updateUserList();
	}
	function onPlayerLeave(data:PlayerData)
	{
		console.log("<" + data.name+"> has left.");
		chat.onPlayerLeave(data);
		updateUserList();
	}
	function onGameJoin(data)
	{
		console.log("<" + data.name+"> has joined.");
		//chat.onGameJoin(data);
		updateGamesInPlayList();
	}
	function updateHistoryList()
	{
		connection.call("getHistory", new flash.net.Responder(onResultGetHistory, onErrorGetHistory));
	}
	function updateUserList()
	{
		connection.call("getPlayers", new flash.net.Responder(onResultGetPlayers, onErrorGetPlayers));
	}
	public function updateGamesInPlayList()
	{
		connection.call("getGamesInPlay", new flash.net.Responder(onResultGetGamesInPlay, onErrorGetGamesInPlay));
	}
	function onTextInput(user, text):Void
	{
		chat.onTextInput(user, text);
	}
	function onResultGetPlayers(data)
	{
		allPlayers.dataProvider = new DataProvider(data);
		chat.onResultGetPlayers(data);
	}
	function onErrorGetPlayers(obj)
	{
		console.log("Error:"+obj.toString());
	}
	function onResultGetHistory(data)
	{
		gamesHistory.dataProvider = new DataProvider(data);
	}
	function onErrorGetHistory(obj)
	{
		console.log(obj);
	}
	function onResultGetGamesInPlay(games:Array<Dynamic>)
	{
		var playing = [];
		var waiting = [];
		for(i in games)
		{
			if(i.players[1]==null || i.players[1]=="")
				waiting.push(i);
			else
				playing.push(i);
		}
		waitingPlayers.dataProvider = new DataProvider(waiting);
		gamesInPlay.dataProvider = new DataProvider(playing);
	}
	function onErrorGetGamesInPlay(obj)
	{
		console.log(obj);
		//console.log("Error:"+obj.code);
		//console.log("Error:"+obj.level);
	}
}